package com.biodiv.miracle.web.server;

import com.biodiv.miracle.web.servlet.DispatcherServlet;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;

import javax.servlet.Servlet;
import java.io.File;
import java.util.concurrent.CountDownLatch;
import java.util.logging.Logger;


/**
 * @Author: tianquan
 * @CreateTime: 2025-05-25  18:36
 * @Description: Tomcat服务器
 */
public class TomcatServer implements WebServer {

    private final Logger logger = Logger.getLogger(TomcatServer.class.getName());
    private Tomcat tomcat;
    private Integer port = 8080;
    private final Servlet servlet;
    public static final CountDownLatch COUNT_DOWN_LATCH = new CountDownLatch(1);

    public TomcatServer(DispatcherServlet servlet) {
        this.servlet = servlet;
    }

    @Override
    public void start() {
        new Thread(() -> {
            try {
                tomcat = new Tomcat();
                tomcat.setPort(port);
                Context context = tomcat.addContext("/", new File(".").getAbsolutePath());
                Tomcat.addServlet(context, "dispatcherServlet", servlet);
                context.addServletMappingDecoded("/*", "dispatcherServlet");
                tomcat.start();
                COUNT_DOWN_LATCH.countDown();
                tomcat.getServer().await();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
        try {
            COUNT_DOWN_LATCH.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void stop() {
        try {
            tomcat.stop();
        } catch (LifecycleException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int getPort() {
        return this.port;
    }

    @Override
    public void setPort(int port) {
        this.port = port;
    }

}
